package com.ejb.controller;

import com.entity.Invitee;
import com.ejb.controller.util.JsfUtil;
import com.ejb.controller.util.PaginationHelper;
import com.ejb.InviteeFacade;

import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

@ManagedBean(name = "inviteeController")
@SessionScoped
public class InviteeController implements Serializable {

    private Invitee current;
    private DataModel items = null;
    private DataModel guest = null;
    private DataModel invitee = null;
    private DataModel myInvitation = null;
    @EJB
    private com.ejb.InviteeFacade ejbFacade;
    @EJB
    private com.ejb.UserFacade userEjbFacade;
    @EJB
    private com.ejb.EventFacade eventEjbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @PersistenceContext
    private EntityManager em;
    
    public InviteeController() {
    }
    
    public DataModel viewGuest(){
        
        return guest;
    }

    public DataModel getMyInvitation() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        
        setMyInvitation(new ListDataModel(em.createNamedQuery("Invitee.findByUserEmail",Invitee.class).setParameter("userEmail", userEjbFacade.find(request.getUserPrincipal().getName())).getResultList()) );
        return myInvitation;
    }

    public void setMyInvitation(DataModel myInvitation) {
        this.myInvitation = myInvitation;
    }
    
    public String myInvitationEdit() {
        //current = null;
        current = (Invitee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "invitationEdit";
    }
    
    public DataModel getGuest() {
        setGuest(new ListDataModel(em.createNamedQuery("Invitee.findByAccepted",Invitee.class).setParameter("accepted", true).getResultList()) );
        return guest;
    }

    public void setGuest(DataModel guest) {
        this.guest = guest;
    }

    public DataModel getInvitee() {
        return invitee;
    }

    public void setInvitee(DataModel invitee) {
        this.invitee = invitee;
    }
    
    
    
    public Invitee getSelected() {
        if (current == null) {
            current = new Invitee();
            selectedItemIndex = -1;
        }
        return current;
    }

    private InviteeFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    FacesContext context = FacesContext.getCurrentInstance();
                    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
                    return em.createNamedQuery("Invitee.findByUserEmail",Invitee.class).setParameter("userEmail", userEjbFacade.find(request.getUserPrincipal().getName())).getResultList().size();
                }

                @Override
                public DataModel createPageDataModel() {
                    FacesContext context = FacesContext.getCurrentInstance();
                    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
                    List<Invitee> invitee;
                    invitee = em.createNamedQuery("Invitee.findByUserEmail",Invitee.class).setParameter("userEmail", userEjbFacade.find(request.getUserPrincipal().getName())).getResultList();
                    
                    if(getPageFirstItem() + getPageSize()> invitee.size())
                        return new ListDataModel(invitee.subList(getPageFirstItem(), invitee.size()));
                    else
                        return new ListDataModel(invitee.subList(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                    //return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Invitee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Invitee();
        selectedItemIndex = -1;
        return "Create";
    }

    public String invitationCreate() {
        current = new Invitee();
        selectedItemIndex = -1;
        return "invitationCreate";
    }
    
    public String inviteeCreate(int eventID) {
        try {
            current.setId(getFacade().findAll().get(getFacade().count()-1).getId()+1);
            current.setEventID(eventEjbFacade.find(eventID));
            current.setUserEmail(getSelected().getUserEmail());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("InviteeCreated"));
            return getEventList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    public String getEventList() {
        current = new Invitee();
        selectedItemIndex = -1;
        return "/faces/user/eventList";
    }
    
    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("InviteeCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Invitee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }
    
    public String invitationUpdate() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("InviteeUpdated"));
            return "invitationView";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("InviteeUpdated"));
            return "/faces/user/invitationView";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String inviteeDestroy() {
        current = (Invitee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "invitationView";
    }
    public String destroy() {
        current = (Invitee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("InviteeDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String nextPage() {
        getPagination().nextPage();
        recreateModel();
        return "invitationView";
    }

    public String previousPage() {
        getPagination().previousPage();
        recreateModel();
        return "invitationView";
    }
    
    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Invitee.class)
    public static class InviteeControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            InviteeController controller = (InviteeController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "inviteeController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Invitee) {
                Invitee o = (Invitee) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Invitee.class.getName());
            }
        }

    }

}
